package designpostproduct

import (
	// "net/http"

	// "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"

	// "github.com/jinzhu/gorm"

	"oxy_server/model"
	"oxy_server/module/log"
)

type (
	DesignProductRel struct {
		ID               bson.ObjectId `json:"_id" bson:"_id"`
		DesignId         string        `json:"designid" bson:"designid"`                 //设计组id
		ProductId        string        `json:"productid" bson:"productid"`               //生产组id
		Status           bool          `json:"status" bson:"status"`                     //是否可以同步
		Largecargonumber string        `json:"largecargonumber" bson:"largecargonumber"` //大货号

	}
	insertDesignProductRel struct {
		DesignId         string `json:"designid" bson:"designid"`                 //设计组id
		ProductId        string `json:"productid" bson:"productid"`               //生产组id
		Status           bool   `json:"status" bson:"status"`                     //是否可以同步
		Largecargonumber string `json:"largecargonumber" bson:"largecargonumber"` //大货号
	}
)

type OXYDesignProductData struct{}

func NewOXYDesignProductData() *OXYDesignProductData {
	data := &OXYDesignProductData{}
	return data
}

func (ohs *OXYDesignProductData) GetInfoHandler(c echo.Context) error {
	log.Info("GetInfoHandler")
	id := c.QueryParam("id")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_product_rel"
	query, err := model.DB().QueryOne(bson.M{"designid": id})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := DesignProductRel{}
	query.One(&p)
	if err != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": p,
	})

	return nil
}

func (ohs *OXYDesignProductData) AddHandler(c echo.Context) error {
	log.Info("AddHandler")
	o := &insertDesignProductRel{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_product_rel"
	err := model.DB().Insert(o)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (ohs *OXYDesignProductData) UpdateHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateHandler", id)
	o := &insertDesignProductRel{}
	if err := c.Bind(o); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_product_rel"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, o)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})
	return nil
}
